<template>
  <permission-check type="exam" class="registration-page ">
    <div class="registration-container ">
      <!-- 搜索表单 -->
      <div class="search-form ">
        <el-form :model="searchForm" inline class="search-form-content">
      
            <el-form-item label="考生姓名" class="el-form-item">
              <el-input v-model="searchForm.candidateName" placeholder="请输入考生姓名" clearable />
            </el-form-item>
            <el-form-item label="授权名称" class="el-form-item">
              <el-input v-model="searchForm.username" placeholder="请输入授权名称" clearable />
            </el-form-item>
            <el-form-item label="证件号码" class="el-form-item">
              <el-input v-model="searchForm.idNumber" placeholder="请输入证件号码" clearable />
            </el-form-item>
            <el-form-item label="报考专业" class="el-form-item">
              <el-select v-model="searchForm.major" placeholder="请选择报考专业" clearable>
                <el-option v-for="item in majorData" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考等级" class="el-form-item">
              <el-select v-model="searchForm.level" placeholder="请选择报考等级" clearable>
                <el-option v-for="item in levelData" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考日期" class="el-form-item">
              <el-date-picker
                v-model="searchForm.applicationDate"
                type="date"
                placeholder="请选择报考日期"
                value-format="YYYY-MM-DD"
                />
          </el-form-item>
            <!-- <el-form-item label="授权名称" class="el-form-item">
              <el-select v-model="searchForm.user_id" placeholder="请选择授权名称" clearable>
                <el-option v-for="item in organizationOptions" :key="item.id" :label="item.username" :value="item.id" />
              </el-select>
            </el-form-item> -->
           
            <el-form-item>
              <el-button type="primary" @click="handleSearch" class="Button">搜索</el-button>
              <el-button @click="resetSearch" class="Button">重置</el-button>
            </el-form-item>
         
            <el-form-item >
              <el-button type="primary" class="Button" :loading="downloadLoadingV1" @click="handleBatchList" :disabled="!tableData.length" :title="!tableData.length ? '暂无数据可导出' : ''">
                <el-icon><Download /></el-icon>
                导出报名列表
              </el-button>
            </el-form-item>
            <el-form-item >
              <el-button type="primary" class="Button" :loading="downloadLoadingV2" @click="handleBatchExport" :disabled="!tableData.length" :title="!tableData.length ? '暂无数据可导出' : ''">
                <el-icon><Download /></el-icon>
                批量导出报名表
              </el-button>
            </el-form-item>
        
        </el-form>
      </div>

      <!-- 添加表格容器 -->
      <el-table v-loading="loading" :data="tableData" border class="el-table">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="candidateName" label="考生姓名" width="100"/>
          <el-table-column prop="candidateNamePinyin" label="姓名拼音" width="180"/>
          <el-table-column prop="gender" label="考生性别" width="100"/>
          <el-table-column prop="major" label="报考专业" width="100"/>
          <el-table-column prop="level" label="报考等级" width="100"/>
          
          <el-table-column prop="ethnicity" label="民族" width="100"/>
          <el-table-column prop="idType" label="证件类型" width="120"/>
          <el-table-column prop="idNumber" label="证件号码" width="180"/>
          
          <el-table-column prop="createdAt" label="报名时间" width="160"/>
          
          <el-table-column prop="currentAddress" label="现居地址" width="200"/>
          <el-table-column prop="username" label="授权名称" width="280"/>
          <el-table-column label="操作" width="310" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" @click="handleEdit(row)"> 编辑/查看 </el-button>
              <el-button type="primary" @click="handleViewForm(row)">
                <el-icon><Document /></el-icon>
                报名表
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
             <el-empty description="暂无数据" />
           </template>
      </el-table>
  

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[15, 20, 50, 100,200]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>

      <!-- 编辑弹框 -->
      <el-dialog v-model="dialogVisible" title="编辑/查看" width="600px" class="edit-dialog" :close-on-click-modal="false">
        <div class="dialog-content">
          <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" class="edit-form">
            <el-form-item label="考生姓名" prop="candidateName">
              <el-input v-model="editForm.candidateName" />
            </el-form-item>
            <el-form-item label="姓名拼音" prop="candidateNamePinyin">
              <el-input v-model="editForm.candidateNamePinyin" />
            </el-form-item>
            <el-form-item label="考生性别" prop="gender">
              <el-select v-model="editForm.gender">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="民族" prop="ethnicity">
              <el-select v-model="editForm.ethnicity" placeholder="请选择民族">
                <el-option v-for="item in Ethnicity" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="国籍" prop="nationality">
              <el-select v-model="editForm.nationality" placeholder="请选择国籍">
                <el-option v-for="item in Nationality" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="idNumber">
              <el-input v-model="editForm.idNumber" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker v-model="editForm.birthDate" type="date" placeholder="选择出生日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="报考专业" prop="major">
              <el-select v-model="editForm.major" placeholder="请选择报考专业">
                <el-option v-for="item in editForm.specialties || []" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考等级" prop="level">
              <el-select v-model="editForm.level" placeholder="请选择报考等级">
                <el-option v-for="i in 10" :key="i" :label="`${i}级`" :value="`${i}级`" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考日期" prop="applicationDate">
              <el-date-picker v-model="editForm.applicationDate" type="date" placeholder="选择报考日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="报名机构" prop="institution">
              <el-select v-model="editForm.institution" placeholder="请选择报考机构">
                <el-option :key="1" :label="editForm.institution" :value="editForm.institution" />
              </el-select>
            </el-form-item>
            <el-form-item label="所在校区" prop="campus">
              <el-select v-model="editForm.campus" placeholder="请选择所在校区">
                <el-option v-for="item in editForm.campuses || []" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="现居地址" prop="currentAddress">
              <el-input v-model="editForm.currentAddress" />
            </el-form-item>
            <el-form-item label="家长电话" prop="parentPhone">
              <el-input v-model="editForm.parentPhone" />
            </el-form-item>
            <el-form-item label="指导老师" prop="instructor">
              <el-input v-model="editForm.instructor" />
            </el-form-item>
            <el-form-item label="老师电话" prop="instructorPhone">
              <el-input v-model="editForm.instructorPhone" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </permission-check>
</template>

<script setup>
  import {Ethnicity,Nationality} from '@/utils/files.js'
  import PermissionCheck from '@/components/PermissionCheck.vue';
  import { ref, reactive, onMounted, watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Document, Delete, Download } from '@element-plus/icons-vue';
  import Http from '@/utils/http';
  import { areaOptions } from '@/utils/area-data';
  import OSS from 'ali-oss';
  import { imgUrls } from '@/utils/utils';
  import { useMainStore } from '@/stores/useMain';
  const mainStore = useMainStore();


  const majorData = ref(['主持']);
  const levelData = ref(['1级','2级','3级','4级','5级','6级','7级','8级','9级','10级']);
  // 搜索表单数据
  const searchForm = reactive({
    candidateName: '', // 考生姓名
    user_id: '', // 授权名称
    examApplicationId: '', // 考试申报ID
    username:'', // 授权名称
    idNumber:'', // 证件号码
    major:'',  // 专业
    level:'',  // 等级
    applicationDate:'',// 报考日期
  });

  // 表格数据
  const loading = ref(false);
  const tableData = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(15);
  const total = ref(0);

  // 机构和考试选项
  const organizationOptions = ref([]);
  const examOptions = ref([]);

  // 编辑弹框相关
  const dialogVisible = ref(false);
  const editFormRef = ref(null);
  const editForm = reactive({
    id: '',
    candidateName: '',
    candidateNamePinyin: '',
    gender: '',
    ethnicity: '',
    nationality: '',
    idNumber: '',
    birthDate: '',
    major: '',
    level: '',
    applicationDate: '',
    institution: '',
    campus: '',
    currentAddress: '',
    parentPhone: '',
    instructor: '',
    instructorPhone: '',
    specialties: [],
    campuses: [],
  });
  const downloadLoadingV1 = ref(false);
  const downloadLoadingV2 = ref(false);
  // 表单验证规则
  const rules = {
    candidateName: [{ required: true, message: '请输入考生姓名', trigger: 'blur' }],
    candidateNamePinyin: [{ required: true, message: '请输入姓名拼音', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    ethnicity: [{ required: true, message: '请输入民族', trigger: 'blur' }],
    nationality: [{ required: true, message: '请输入国籍', trigger: 'blur' }],
    idNumber: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
    birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
    major: [{ required: true, message: '请输入报考专业', trigger: 'blur' }],
    level: [{ required: true, message: '请输入报考等级', trigger: 'blur' }],
    applicationDate: [{ required: true, message: '请选择报考日期', trigger: 'change' }],
    institution: [{ required: true, message: '请输入报考机构', trigger: 'blur' }],
    campus: [{ required: true, message: '请输入所在校区', trigger: 'blur' }],
    currentAddress: [{ required: true, message: '请输入现居地址', trigger: 'blur' }],
    parentPhone: [
      { required: true, message: '请输入家长电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    instructor: [{ required: true, message: '请输入指导老师', trigger: 'blur' }],
    instructorPhone: [
      { required: true, message: '请输入指导老师电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
  };

  // 页面初始化
  onMounted(() => {
    getOrganizations();
  });

  // 获取机构列表
  const getOrganizations = async () => {
    try {
      const res = await Http.get({
        url: '/yp_admin/getSubuser',
      });
      organizationOptions.value = res.data.list;

      // 如果只有一条数据，默认选中
      if (organizationOptions.value.length === 1) {
        searchForm.user_id = organizationOptions.value[0].id;
      }

      // 如果有选中的机构，获取对应的考试申报列表
      if (searchForm.user_id) {
        getExams();
      }
      getRegistrations();
    } catch (error) {
      ElMessage.error('获取机构列表失败');
    }
  };

  // 获取考试申报列表
  const getExams = async () => {
    examOptions.value = []; // 清空之前的考试申报列表

    try {
      const params = {
        page: 1,
        pageSize: 1000,
        user_id: searchForm.user_id,
      };
      const res = await Http.post({
        url: '/yp_admin/getExamApplications',
        data: params,
      });
      examOptions.value = res.data.items || [];
    } catch (error) {
      ElMessage.error('获取考试列表失败');
    }
  };

  // 获取报名列表
  const getRegistrations = async () => {
    loading.value = true;
    try {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        candidateName: searchForm.candidateName,
        userId: searchForm.user_id,
        examApplicationId: searchForm.examApplicationId,
        username:searchForm.username,
        idNumber:searchForm.idNumber,
        major:searchForm.major,
        level:searchForm.level,
        applicationDate:searchForm.applicationDate,
      };
      const res = await Http.post({
        url: '/yp_admin/applyList',
        data: params,
      });

      // 从 pagination 中获取分页数据
      tableData.value = res.data.list || [];
      if (res.data.pagination) {
        total.value = res.data.pagination.total || 0; // 从 pagination 中获取总数
        // 如果后端返回的当前页与前端不一致，更新前端页码
        if (res.data.pagination.currentPage !== currentPage.value) {
          currentPage.value = res.data.pagination.currentPage;
        }
        // 如果后端返回的每页条数与前端不一致，更新前端每页条数
        if (res.data.pagination.pageSize !== pageSize.value) {
          pageSize.value = res.data.pagination.pageSize;
        }
      }

      // 如果当前页没有数据且不是第一页，回到上一页
      if (tableData.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
        getRegistrations();
      }
    } catch (error) {
      ElMessage.error('获取报名列表失败');
    } finally {
      loading.value = false;
    }
  };

  // 搜索
  const handleSearch = () => {
    currentPage.value = 1;
    getRegistrations();
  };

  // 重置搜索
  const resetSearch = () => {
    Object.keys(searchForm).forEach((key) => {
      searchForm[key] = '';
    });
    handleSearch();
  };

  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val;
    getRegistrations();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getRegistrations();
  };

  // 监听机构变化，重新获取考试列表
  watch(
    () => searchForm.user_id,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        // 只在值真正改变时触发
        searchForm.examApplicationId = ''; // 清空考试选择
        if (newVal) {
          getExams(); // 获取新的考试申报列表
        }
      }
    },
    { immediate: true },
  );

  // 编辑考生信息
  const handleEdit = (row) => {
    dialogVisible.value = true;
    // 复制行数据到编辑表单
    Object.keys(editForm).forEach((key) => {
      editForm[key] = row[key];
    });
    console.log(editForm.value, 'editForm');
  };

  // 提交编辑
  const submitEdit = async () => {
    if (!editFormRef.value) return;

    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const params = {
            id: editForm.id, // 添加id参数
            candidateName: editForm.candidateName,
            candidateNamePinyin: editForm.candidateNamePinyin,
            gender: editForm.gender,
            ethnicity: editForm.ethnicity,
            nationality: editForm.nationality,
            idNumber: editForm.idNumber,
            birthDate: editForm.birthDate,
            major: editForm.major,
            level: editForm.level,
            applicationDate: editForm.applicationDate,
            institution: editForm.institution,
            campus: editForm.campus,
            currentAddress: editForm.currentAddress,
            parentPhone: editForm.parentPhone,
            instructor: editForm.instructor,
            instructorPhone: editForm.instructorPhone,
          };

          const result = await Http.post({
            url: '/yp_admin/editApply', // 修改为正确的接口
            data: params,
          });

          dialogVisible.value = false;
          if (result.code != 200) return ElMessage.error(result.msg);

          ElMessage.success('更新成功');

          getRegistrations(); // 刷新列表
        } catch (error) {
          ElMessage.error('更新失败');
        }
      }
    });
  };

  // 查看报名表
  const handleViewForm = (row) => {
    if (row.registrationForm) {
      const downloadUrl = imgUrls(row.registrationForm);
      window.open(downloadUrl, '_blank');
    } else {
      ElMessage.warning('未找到报名表文件');
    }
  };

  // 删除考生
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除考生 ${row.candidateName} 的报名信息吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await Http.post({
            url: '/yp_admin/deleteApply',
            data: {
              id: row.id,
            },
          });

          if (res.code === 200) {
            ElMessage.success('删除成功');
            getRegistrations(); // 刷新列表
          } else {
            ElMessage.error(res.msg || '删除失败');
          }
        } catch (error) {
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        // 取消删除
      });
  };

  // 添加批量导出方法
  const handleBatchExport = async () => {
    if (!tableData.value.length) {
      ElMessage.warning('暂无数据可导出');
      return;
    }
    downloadLoadingV2.value = true;
    try {
      const res = await Http.post({
        url: '/yp_admin/DownloadRegistrationForm',
        data: {
          candidateName: searchForm.candidateName,
          userId: searchForm.user_id,
          examApplicationId: searchForm.examApplicationId,
          username:searchForm.username,
          idNumber:searchForm.idNumber,
          major:searchForm.major,
          level:searchForm.level,
          applicationDate:searchForm.applicationDate,
        },
      });
     

      if (res.data?.url) {
        const downloadUrl = imgUrls(res.data.url);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '报名表批量导出.zip';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('导出成功');
      } else {
        ElMessage.warning('未找到可下载的文件');
      }
    } catch (error) {
      ElMessage.error('导出失败');
    } finally {
      downloadLoadingV2.value = false;
    }
  };

  // 导出报名列表
  const handleBatchList = async () => {
    if (!tableData.value.length) {
      ElMessage.warning('暂无数据可导出');
      return;
    }
    downloadLoadingV1.value = true;
    try {
      const res = await Http.post({
        url: '/yp_admin/batchDownloadApplyInfo',
        data: {
          candidateName: searchForm.candidateName,
          userId: searchForm.user_id,
          examApplicationId: searchForm.examApplicationId,
          username:searchForm.username,
          idNumber:searchForm.idNumber,
          major:searchForm.major,
          level:searchForm.level,
          applicationDate:searchForm.applicationDate,
        },
      });

      if (res.data?.url) {
        const downloadUrl = imgUrls(res.data.url);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = res.data.fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('导出成功');
      } else {
        ElMessage.warning('未找到可下载的文件');
      }
    } catch (error) {
      ElMessage.error('导出失败');
    } finally {
      downloadLoadingV1.value = false;
    }
  };
</script>

<style scoped lang="scss">

.el-form--inline .el-form-item {
    margin-right: 10px !important;
    :deep(.el-form-item__content) {
      width: 180px !important;
      .el-input{
        height:100%;
      }
    }
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  :deep(.el-input__wrapper) {
   
    height: 40px;
    line-height: 40px;
   
  }
  :deep(.el-form-item__label){
    height:40px;
    line-height: 40px;
  }
 
  

  .registration-page {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden; // 防止溢出
    display: flex;
    flex-direction: column;
  
  }

  .registration-container {
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;

    .search-form {
      width:100%;
      display: flex;
      align-items: center;
      .search-form-content {
        width:100%;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

       
      }
    }
    .el-table {
        flex:1;
        width: 100%;
        overflow: scroll;
      }
    
    .pagination-container {
      padding: 8px 20px;
      background-color: #fff;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  // 修改编辑弹框样式
  .edit-dialog {
    :deep(.el-dialog) {
      margin: 0 auto !important;
      max-height: 88vh; // 进一步减小整体高度
      display: flex;
      flex-direction: column;
      position: relative;
      top: 0;
    }

    :deep(.el-dialog__header) {
      padding: 8px 20px; // 进一步减小头部高度
      margin: 0;
      border-bottom: 1px solid #dcdfe6;
    }

    :deep(.el-dialog__body) {
      padding: 0;
      overflow: hidden;
    }

    :deep(.el-dialog__footer) {
      padding: 8px 20px; // 进一步减小底部高度
      margin: 0;
      border-top: 1px solid #dcdfe6;
    }

    .dialog-content {
      max-height: 58vh; // 减小内容区域高度
      overflow-y: auto;
      padding: 12px 20px; // 减小内边距
    }

    .edit-form {
      :deep(.el-form-item) {
        margin-bottom: 16px; // 稍微调整表单项间距

        // 保持输入框宽度和高度
        .el-input,
        .el-select,
        .el-date-picker {
          width: 400px;
        }

        .el-input__wrapper,
        .el-select .el-input__wrapper {
          height: 40px;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  // 美化滚动条样式
  .dialog-content {
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #dcdfe6;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background: #f5f7fa;
    }

    &::-webkit-scrollbar-corner {
      background: #f5f7fa;
    }
  }
</style>
